//
//  ZYSearchBar.swift
//  ZYSinaWeibo
//
//  Created by 陟岳 on 16/5/20.
//  Copyright © 2016年 陟岳. All rights reserved.
//

import UIKit

class ZYSearchBar: UIView, UITextFieldDelegate {

    //属性
    @IBOutlet weak var textField: UITextField!
    @IBOutlet weak var rightCons: NSLayoutConstraint!
    @IBOutlet weak var cancleBtn: UIButton!
    
    
    //提供加载xib的类方法
    class func loadSearchBar() -> ZYSearchBar {
    
        let searchView = NSBundle.mainBundle().loadNibNamed("ZYSearchBar", owner: nil, options: nil).last as! ZYSearchBar
        
        return searchView
    
    }
    
    //加载xib
    override func awakeFromNib() {
        
        //设置宽
        bounds.size.width = ScreenWidth
        textField.leftView = UIImageView(image: UIImage(named: "searchbar_textfield_search_icon"))
        
        //设置左视图显示模式
        textField.leftViewMode = .Always
        
        //设置左视图的frame
        textField.leftView?.frame = CGRect(x: 0, y: 0, width: 50, height: 40)
        textField.leftView?.contentMode = .Center
        
        //设置代理
        textField.delegate = self
        
        //设置圆角和边线
        textField.layer.borderWidth = 2
        textField.layer.borderColor = UIColor.orangeColor().CGColor
        textField.layer.cornerRadius = 20
        textField.layer.masksToBounds = true
        
    
    }
    
    //取消按钮点击事件
    @IBAction func cancleBtnClick(sender: UIButton) {
        
        self.rightCons.constant = 0
        //动画效果
        UIView.animateWithDuration(0.25) {
            
            self.layoutIfNeeded()
        }
        
        //结束编辑
        self.endEditing(true)
        
    }
    
    //textField的代理方法
    func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
        
        print("开始编辑")
        self.rightCons.constant = self.cancleBtn.bounds.width
        
        //动画效果
        UIView.animateWithDuration(0.25) { 
            
            self.layoutIfNeeded()
        }
        
        return true
    }

}
